<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/30
 * Time: 14:21
 */
namespace App\Http\Controllers;

use App\ErrorCode;
use App\Help\Help;
use App\Models\CarLogo;
use App\Models\File;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

date_default_timezone_set('PRC');
class FileController extends Controller{

    private $type;

    private function checkDomain(){
//        echo '1';exit;
        //域名白名单
        $allowDomain = array(
            'url_1' => '127.0.0.1',
            'url_2' => 'localhost',
            'url_3' => '118.190.44.187',
        );
        $referer = $_SERVER['HTTP_REFERER'];
        if($referer) {
            $refererhost = parse_url($referer);
            $host = strtolower($refererhost['host']);
//            var_dump($host);exit;
            if (!in_array($host, $allowDomain)) {
                return $this->output(false,ErrorCode::DOMAIN_NOT_ALLOW);
//                exit('error');
            }
        }
    }

    private function checkError($error){

        return;
    }

    private function checkType($type){
        //判断文件类型
        $image_type = $type;
        if($image_type == 'application/x-msdownload' || $image_type == 'application/octet-stream' ||
            $image_type == 'application/javascript' || $image_type == 'text/html' || $image_type == 'text/asp'
            || $image_type == 'application/x-php'){
            return $this->output(false,ErrorCode::FILE_NOT_ALLOW);
        } else {
            $filename = $_FILES['file']['name'];
            $extend = pathinfo($filename);
            $type = $extend['extension'];
        }
    }
    public function upload(Request $request){
//        return $_SERVER;


        FileController::checkDomain(); //检查域名
        if(!$request->hasFile('file')){
            return $this->output(false,ErrorCode::UPLOAD_FILE_EMPTY);
        }
        $file=$request->file('file');
        if(!$file->isValid()){
            return $this->output(false,ErrorCode::UPLOAD_FILE_ERROR);
        }
        $file = $request->file('file');
        //获取文件信息
        $error = $file->getError(); //错误信息
        $this->checkError($error); //返回错误信息
        $originalName  = $file->getClientOriginalName(); //文件原名
        $ext = $file->getClientOriginalExtension(); //扩展名
        $realPath = $file->getRealPath();   //临时文件的绝对路径
        $type = $file->getClientMimeType(); //文件类型
        $this->checkType($type); //判断文件类型是否安全
        $size = $file->getClientSize(); //大小
        $fileHash = hash_file('md5',$realPath);
        $fileId = $fileHash.time();
        $filename = $fileHash . '.' . $ext; //存入文件名

        $model = new File();
        $model->name = $originalName;
        $model->type = $type;
        $model->ext = $ext;
//        $model->size = $size;
        $model->fileHash = $fileHash;

        $model->fileId = $fileId;
        //判断文件是否存在
        $exist = DB::table('up_img')->where('fileHash',$fileHash)->first();

        //不存在
        if(empty($exist)){
            $rdate = date('Y-m-d', time());
            if(!file_exists('.././upload/' .$rdate)) {
                mkdir('.././upload/' . $rdate);
            }
            $dir = '.././upload/'.date('Y-m-d', time());
            //移动文件
            if($request->file('file')->move($dir,$filename)){

                $uploadfile = $dir.'/'.$filename;

                $newSize = Help::updateImage($uploadfile,$uploadfile);
                $model->size = $newSize;

                $model->time = date('Y-m-d H:i:s');
                if($model->save()){
                    $result = File::select('name','type','fileId','time')->where('fileId','=',$fileId)->first();
                    return $this->output($result);
                }

            } else {
                return $this->output(false,ErrorCode::UPLOAD_FILE_ERROR);
            }
        } else {
            $array = [];
            foreach ($exist as $key => $value) {
                $array[$key] = $value;
            }
            $model->time = $array['time'];
            $model->size = $array['size'];
            if($model->save()){
                $result = File::select('name','type','fileId','time')->where('fileId','=',$fileId)->first();
                return $this->output($result);
            }

        }
    }

    public function getFile(Request $request){

        $fileId = $request->get('fileId');

        $ret = File::where('fileId','=',$fileId)->first();
        if($ret){

            $time = strtotime($ret['time']);
            $dir = date('Y-m-d', $time);
            $type = $ret['type'];
            $filename = $ret['fileHash'] . '.' . $ret['ext'];
            $server = preg_replace("#/[^/]*$#", "", $_SERVER['DOCUMENT_ROOT']);
//            $server = $server.'/php';
//            $server = $server.'/productApi';
            $path = $server . '/upload/' . $dir . '/' . $filename;

//            $path = $_SERVER['DOCUMENT_ROOT'] . '/CARBase/upload/' . $dir . '/' . $filename;
//            echo $path;exit;
            header("Content-type:$type");
            header("Accept-Ranges:bytes");
//                    header("Accept-Length:".$file_Size);
            ob_start();
            readfile($path);
            ob_end_flush();
        } else {
            return $this->output(false,ErrorCode::FILE_NOT_EXIST);
        }
    }

    public function download(Request $request){

//        $this->checkDomain(); //检查域名
        $fileId = $request->get('fileId');
        $ret = File::where('fileId','=',$fileId)->first();
        if($ret){

            $time = strtotime($ret['time']);
            $dir = date('Y-m-d', $time);
            $type = $ret['type'];
            $ext = $ret['ext'];
            $filename = $ret['fileHash'] . '.' . $ext;
            $server = preg_replace("#\/[^\/]*$#", "", $_SERVER['DOCUMENT_ROOT']);
            $path = $server . '/upload/' . $dir . '/' . $filename;
//            $path = $_SERVER['DOCUMENT_ROOT'] . '/CARBase/upload/' . $dir . '/' . $filename;
            //判断路径是否存在
            if (!file_exists($path)) {
                return $this->output(false,ErrorCode::FILE_NOT_EXIST);
            }
            $fp = fopen($path, "r");
            //取得文件大小
            $file_Size = $ret['size'];

            header("Content-type:$type");
            header("Content-type:application/octet-stream");
            header("Accept-Ranges:bytes");
            header("Accept-Length:" . $file_Size);
            header("Content-Disposition: attachment; filename=" . $ret['name']);

            $buffer = 1024;
            $buffer_count = 0;
            //判断文件是否结束
            while (!feof($fp) && $file_Size - $buffer_count > 0) {
                $data = fread($fp, $buffer);
                $buffer_count += $buffer;

                echo $data;

            }
            fclose($fp);
        } else {
            return $this->output(false,ErrorCode::FILE_NOT_EXIST);
        }
    }

    public function delete(Request $request){

//        $this->checkDomain(); //检查域名
        $fileId = $request->get('fileId');
        $ret = File::where('fileId','=',$fileId)->delete();
        if($ret){
            return $this->output('删除成功');
        } else {
            return $this->output(false,ErrorCode::DELETE_FAILED);
        }
    }

    public static function getPath($fileId){

//        $fileId = $request->input('fileId');
        $ret = File::where('fileId','=',$fileId)->first();
        if($ret){
            $time = strtotime($ret['time']);
            $dir = date('Y-m-d', $time);
//            $type = $ret['type'];
            $ext = $ret['ext'];
            $filename = $ret['fileHash'] . '.' . $ext;
            $server = preg_replace("#\/[^\/]*$#", "", $_SERVER['DOCUMENT_ROOT']);
            $path = $server . '/upload/' . $dir . '/' . $filename;
//            $path = $_SERVER['DOCUMENT_ROOT'] . '/CARBase/upload/' . $dir . '/' . $filename;
            return $path;
        }
    }

    public function carLogoUpload(Request $request){
        FileController::checkDomain(); //检查域名

        if(!$request->hasFile('file')){
            return $this->output(false,ErrorCode::UPLOAD_FILE_EMPTY);
        }
        $file=$request->file('file');
        if(!$file->isValid()){
            return $this->output(false,ErrorCode::UPLOAD_FILE_ERROR);
        }
        $file = $request->file('file');
        //获取文件信息
        $error = $file->getError(); //错误信息
        $this->checkError($error); //返回错误信息
        $originalName  = $file->getClientOriginalName(); //文件原名
        $ext = $file->getClientOriginalExtension(); //扩展名
        $realPath = $file->getRealPath();   //临时文件的绝对路径
        $type = $file->getClientMimeType(); //文件类型
        $this->checkType($type); //判断文件类型是否安全
        $size = $file->getClientSize(); //大小
        $fileHash = hash_file('md5',$realPath);
        $fileId = $fileHash.time();
        $filename = $fileHash . '.' . $ext; //存入文件名

        $name = $request->input('name');
        if(!empty($name)){
            DB::table('car')
                ->where('carName','LIKE','%' . $name . '%')
                ->update(['carLogo' => $fileId]);
        }

        $model = new CarLogo();
        $model->name = $originalName;
        $model->type = $type;
        $model->ext = $ext;
//        $model->size = $size;
        $model->fileHash = $fileHash;

        $model->fileId = $fileId;
        //判断文件是否存在
        $exist = DB::table('carLogo')->where('fileHash',$fileHash)->first();

        //不存在
        if(empty($exist)){

            $dir = '.././upload/carLogo';
            //移动文件
            if($request->file('file')->move($dir,$filename)){

                $uploadfile = $dir.'/'.$filename;

                $newSize = Help::updateImage($uploadfile,$uploadfile);
                $model->size = $newSize;

                $model->time = date('Y-m-d H:i:s');
                if($model->save()){
                    $result = CarLogo::select('name','type','fileId','time')->where('fileId','=',$fileId)->first();
                    return $this->output($result);
                }

            } else {
                return $this->output(false,ErrorCode::UPLOAD_FILE_ERROR);
            }
        } else {
            $array = [];
            foreach ($exist as $key => $value) {
                $array[$key] = $value;
            }
            $model->time = $array['time'];
            $model->size = $array['size'];
            if($model->save()){
                $result = CarLogo::select('name','type','fileId','time')->where('fileId','=',$fileId)->first();
                return $this->output($result);
            }

        }
    }

    public function getCarLogo(Request $request){
        $fileId = $request->get('fileId');
        $ret = CarLogo::where('fileId','=',$fileId)->first();
        if($ret){

//            $time = strtotime($ret['time']);
//            $dir = date('Y-m-d', $time);
            $type = $ret['type'];
            $filename = $ret['fileHash'] . '.' . $ret['ext'];
            $server = preg_replace("#\/[^\/]*$#", "", $_SERVER['DOCUMENT_ROOT']);
            $path = $server . '/upload/carLogo/' . $filename;
//            $path = $_SERVER['DOCUMENT_ROOT'] . '/CARBase/upload/' . $dir . '/' . $filename;
//            echo $path;exit;
            header("Content-type:$type");
            header("Accept-Ranges:bytes");
//                    header("Accept-Length:".$file_Size);
            ob_start();
            readfile($path);
            ob_end_flush();
        } else {
            return $this->output(false,ErrorCode::FILE_NOT_EXIST);
        }
    }


}